package cn.iocoder.yudao.module.erp.convert.exchange;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.module.erp.controller.admin.exchange.vo.item.ErpExchangeOrderItemBaseVO;
import cn.iocoder.yudao.module.erp.controller.admin.exchange.vo.order.ErpExchangeOrderCreateReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.exchange.vo.order.ErpExchangeOrderRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.exchange.vo.order.ErpExchangeOrderUpdateReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.exchange.ErpExchangeOrderDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.exchange.ErpExchangeOrderItemDO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

import java.util.List;
import java.util.Map;

/**
 * ERP 旧料兑换订单 Convert
 */
@Mapper
public interface ErpExchangeOrderConvert {

    ErpExchangeOrderConvert INSTANCE = Mappers.getMapper(ErpExchangeOrderConvert.class);

    ErpExchangeOrderDO convert(ErpExchangeOrderCreateReqVO bean);

    ErpExchangeOrderDO convert(ErpExchangeOrderUpdateReqVO bean);

    ErpExchangeOrderRespVO convert(ErpExchangeOrderDO bean);

    List<ErpExchangeOrderRespVO> convertList(List<ErpExchangeOrderDO> list);

    PageResult<ErpExchangeOrderRespVO> convertPage(PageResult<ErpExchangeOrderDO> page);

    ErpExchangeOrderItemDO convert(ErpExchangeOrderItemBaseVO bean);
    
    default PageResult<ErpExchangeOrderRespVO> convertPage(PageResult<ErpExchangeOrderDO> pageResult,
                                                           List<ErpExchangeOrderItemDO> items) {
        Map<Long, List<ErpExchangeOrderItemDO>> itemMap = CollectionUtils.convertMultiMap(items, ErpExchangeOrderItemDO::getOrderId);
        List<ErpExchangeOrderRespVO> voList = CollectionUtils.convertList(pageResult.getList(), order -> {
            ErpExchangeOrderRespVO orderVO = convert(order);
            // 设置对应的订单项
            if (itemMap.containsKey(order.getId())) {
                // 按照 sort 升序排序
                List<ErpExchangeOrderItemDO> orderItems = CollUtil.sort(itemMap.get(order.getId()),
                        (o1, o2) -> o1.getSort().compareTo(o2.getSort()));
                // TODO: 需要设置对应的项
            }
            return orderVO;
        });
        return new PageResult<>(voList, pageResult.getTotal());
    }

    default ErpExchangeOrderRespVO convert(ErpExchangeOrderDO order, List<ErpExchangeOrderItemDO> items) {
        ErpExchangeOrderRespVO orderVO = convert(order);
        // 设置对应的订单项
        if (CollUtil.isNotEmpty(items)) {
            // 按照 sort 升序排序
            List<ErpExchangeOrderItemDO> sortedItems = CollUtil.sort(items,
                    (o1, o2) -> o1.getSort().compareTo(o2.getSort()));
            // TODO: 需要设置对应的项
        }
        return orderVO;
    }

} 